<?php
// $Id$

/**
 * Controller_Admin_Mail 控制器
 */
class Controller_Admin_Mail extends Controller_Abstract
{

    function actionCfgMailPlan()
    {
        $mailAddressPlan = Mail_Address_Plan::findById($this->_context->mail_address_plan_id)->getOne();
        if (!$mailAddressPlan->id()) throw new Exception('No mail address plan id.');

        $cfg = array();

        if (isset($this->_context->mail_plan_next_tpl_num)) $cfg['next_tpl_num'] = $this->_context->mail_plan_next_tpl_num;
        if (isset($this->_context->mail_plan_start_date)) $cfg['start_date'] = $this->_context->mail_plan_start_date;
        if (isset($this->_context->mail_plan_address_to_id)) $cfg['mail_address_id'] = $this->_context->mail_plan_address_to_id;
        if (isset($this->_context->mail_plan_status)) $cfg['status'] = $this->_context->mail_plan_status;

        try {
            $mailAddressPlan->saveCfg($cfg);

            $ret = array(
                'ack' => 'success'
            );
        } catch (Exception $e) {
            $ret = array(
                'ack' => 'error',
                'msg' => $e->getMessage()
            );
        }


        return json_encode($ret);
    }

    function actionPlan()
    {
        $plans = Mail_Plan::find()->order('name')->getAll();
        $this->_view['mailPlans'] = $plans;
    }

    function actionAddress()
    {
        $addresses = Mail_Address::find()->getAll();
        $this->_view['addresses'] = $addresses;
    }

    function actionAddressEdit()
    {
        $a = Mail_Address::findById($this->_context->aid)->getOne();

        if ($this->_context->isPost()) {

            $a->changeProps($_POST);

            try {
                $a->save();

                return $this->_redirect(url('.', 'aid/' . $a->id()));

            } catch (QDB_ActiveRecord_ValidateFailedException  $e) {
                $this->_view['errorMsg'] = '错误：' . $e->getMessage();
            }
        }

        $this->_view['a'] = $a;
        $this->_view['title'] = $a->id() ? '编辑邮箱地址' : '添加邮箱地址';
    }

    function actionPlanBindTpl()
    {
        $plan = Mail_Plan::findById($this->_context->mail_plan_id)->getOne();
        $tpls = Mail_Tpl::findByIds($this->_context->tplIds)->getAll();
        $successPlanTpls = $plan->bindTpls($tpls);
        $plan->save();

        if ($this->_context->isAJAX()) {
            $planTplsData = array();
            foreach ($successPlanTpls as $successPlanTpl) {
                $planTplsData[] = array(
                    'mail_plan_tpl_id' => $successPlanTpl->id(),
                    'mail_tpl_id' => $successPlanTpl->mail_tpl_id,
                    'name' => $successPlanTpl->name(),
                    'subject' => $successPlanTpl->subject(),
                    'type' => $successPlanTpl->type(),
                    'profession' => $successPlanTpl->profession(),
                );
            }

            $ret = array(
                'ack' => 'success',
                'planTpls' => $planTplsData,
            );

            return json_encode($ret);
        }
    }

    function actionPlanBindAddress()
    {
        $plan = Mail_Plan::findById($this->_context->mail_plan_id)->getOne();
        $addresses = Mail_Address::findByIds($this->_context->addressIds)->getAll();
        $successPlanAddresses = $plan->bindAddresses($addresses);
        $plan->save();

        if ($this->_context->isAJAX()) {
            $planAddressesData = array();
            foreach ($successPlanAddresses as $successPlanAddress) {
                $planAddressesData[] = array(
                    'mail_plan_address_id' => $successPlanAddress->id(),
                    'mail_address_id' => $successPlanAddress->mail_address_id,
                );
            }

            $ret = array(
                'ack' => 'success',
                'planTpls' => $planAddressesData,
            );

            return json_encode($ret);
        }
    }

    function actionPlanUnbindTpl()
    {
        $planTpl = Mail_Plan_Tpl::findById($this->_context->mail_plan_tpl_id)->getOne();
        try {
            $planTpl->destroy();
            $res = array(
                'ack' => 'success',
            );
        } catch (Exception $e) {
            $res = array(
                'ack' => 'error',
                'msg' => $e->getMessage(),
            );
        }

        return json_encode($res);
    }

    function actionPlanEdit()
    {
        $plan = Mail_Plan::findById($this->_context->pid)->getOne();

        if ($this->_context->isPost()) {
            try {
                $plan->saveData($_POST);

                return $this->_redirect(url('.', 'pid/' . $plan->id()));

            } catch (Exception  $e) {
                $this->_view['errorMsg'] = '错误：' . $e->getMessage();
            }
        }

        if ($plan->id()) {
            $this->_view['title'] = '编辑邮件计划';
        } else {
            $this->_view['title'] = '新增邮件计划';
        }
        $this->_view['plan'] = $plan;

    }

    function actionTpl()
    {
        $tpls = Mail_Tpl::find()->columns('mail_tpl_id,name,subject')->order('name')->getAll();

        if ($this->_context->isAjax()) {
            return $tpls->toAjax();
        }

        $this->_view['tpls'] = $tpls;
    }

    function actionTplEdit()
    {
        $tpl = Mail_Tpl::findById($this->_context->tid)->getOne();

        if ($this->_context->isPost()) {

            $tpl->changeProps($_POST);

            try {
                $tpl->save();
                $tpl->saveUploadFile();

                return $this->_redirect(url('.', 'tid/' . $tpl->id()));

            } catch (QDB_ActiveRecord_ValidateFailedException  $e) {
                $this->_view['errorMsg'] = '错误：' . $e->getMessage();
            }catch(QDB_ActiveRecord_ExpectsAssocPropException $e){
                if($e->prop_name == 'type')
                    $this->_view['errorMsg'] = '错误：请选择模板分类';
                elseif($e->prop_name == 'profession')
                    $this->_view['errorMsg'] = '错误：请选择行业分类';
            }
        }

        if ($tpl->id()) {
            $this->_view['title'] = '编辑邮件模板';
        } else {
            $this->_view['title'] = '新增邮件模板';
        }
        $this->_view['mail'] = $tpl;

        $this->_forward('/edit');
    }

    function actionEdit()
    {
        // edit the real mail

    }

    function actionDel()
    {
        if ($this->_context->tid) {
            $item = Mail_Tpl::findById($this->_context->tid)->getOne();
            if ($item->id()) $item->destroy();

        } elseif ($this->_context->pid) {
            $item = Mail_Plan::findById($this->_context->pid)->getOne();
            if ($item->id()) $item->destroy();
            return $this->_redirect(url('/plan'));
        } elseif ($this->_context->aid) {
            $item = Mail_Address::findById($this->_context->aid)->getOne();
            if ($item->id()) $item->destroy();

            if ($this->_context->isAJAX()) {
                $ret = array(
                    'ack' => 'success',
                );

                return json_encode($ret);
            } else {
                return $this->_redirect(url('/address'));
            }
        }

        return $this->_redirect(url('/tpl'));

    }

    function actionResortPlanTpl()
    {
        try {
            Mail_Plan::resortTpls(array('planTplIds' => $this->_context->planTplIds));
            $ret = array(
                'ack' => 'success',
            );
        } catch (Exception $e) {
            $ret = array(
                'ack' => 'error',
                'msg' => $e->getMessage()
            );
        }
        return json_encode($ret);
    }

    function actionAddType()
    {
        try {
            $newType = Mail_Type::saveData($_POST);
            $res = array(
                'ack' => 'success',
                'newType' => array(
                    'name' => $newType->name,
                    'mail_type_id' => $newType->id(),
                )
            );
        } catch (Exception $e) {
            $res = array(
                'ack' => 'error',
                'msg' => $e->getMessage(),
            );
        }

        return json_encode($res);
    }
}


